package cn.bonoon.controllers;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.bonoon.controllers.parsers.TabsPanelParser;
import cn.bonoon.core.ConfigService;
import cn.bonoon.kernel.ITabHandler;
import cn.bonoon.kernel.events.BaseEvent;
import cn.bonoon.kernel.events.PanelEvent;
import cn.bonoon.kernel.menus.ModuleManager;
import cn.bonoon.kernel.menus.TabInfo;
import cn.bonoon.kernel.menus.TabItem;
import cn.bonoon.kernel.security.PrivilegeChecker;
import cn.bonoon.kernel.support.services.UserService;
import cn.bonoon.kernel.web.controllers.AbstractLayoutController;
import cn.bonoon.kernel.web.controllers.PanelParser;
import cn.bonoon.kernel.web.handlers.IExecutable;
import cn.bonoon.kernel.web.models.StandardModel;

@Controller
@RequestMapping("s/sys/tabs")
public class TabsController extends AbstractLayoutController{
	private final ConfigService configService;
	
	@Autowired
	public TabsController(ConfigService configService){
		this.configService = configService;
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		super.afterPropertiesSet();
		//对所有tabs和tab进行处理
		for(TabItem ti : moduleManager.tabItems()){
			ITabHandler handler = ti.getParser().parse(autoManager);
			if(null != handler){
				autoManager.register(handler);
			}
		}
	}
	
	@Override
	protected PanelParser buildParser(ModuleManager moduleManager, UserService userService) {
		return new TabsPanelParser(moduleManager, userService);
	}
	
	@Override
	protected void onLoad(PanelEvent event) throws Exception {
		List<TabItemInfo> items = new ArrayList<TabItemInfo>();
		PrivilegeChecker privilege = event.getPrivilege();
		for(TabItem ti : ((TabInfo)event.getItem()).getItems()){
			if(privilege.hasPrivilege(ti)){
				items.add(new TabItemInfo(ti));
			}
		}
		event.getModel().addObject("items", items);
		event.setVmPath("sys/sys-tabs");
	}
	
	@Override
	protected Object __execute(IExecutable handler, HttpServletRequest request, Object params, String mid) throws Exception {
		if(handler instanceof ITabHandler){
			BaseEvent event = new BaseEvent(getUser(), params);
			StandardModel model = new StandardModel(mid, request);
			return ((ITabHandler) handler).read(configService, event, model);
		}
		return super.__execute(handler, request, params, mid);
	}
	
	@Override
	protected Object __ajax(IExecutable handler, HttpServletRequest request, Object params, String mid) throws Exception {
		if(handler instanceof ITabHandler){
			BaseEvent event = new BaseEvent(getUser(), params);
			return ((ITabHandler) handler).save(configService, event);
		}
		return super.__ajax(handler, request, params, mid);
	}
}
